<script setup>
import {
  User,
  Lock,
  CircleCheck
} from '@element-plus/icons-vue'
import { ref, watch } from 'vue'

// 导入路由
import { useRouter } from 'vue-router'

// 导入doctor的api
import {
  doctorRegisterService,
  doctorLoginService
} from '@/api/doctor'

// 导入doctor仓库
import { useDoctorStore } from '@/stores/doctorStore'

// 导入图片验证码
import IdentifyPicture from '@/components/identify/IdentifyPicture.vue'

// 导入图片
import image1 from '@/assets/image/login/01.png'
import image2 from '@/assets/image/login/02.png'

// 创建userDocter仓库
const doctorStore = useDoctorStore()

// 创建router实例
const router = useRouter()

// 登录注册切换
const isRegister = ref(false)

// 左侧轮播图图片
const imageList = [image1, image2]

// 创建表单对象, 用于存储表单数据
const formModel = ref({
  // 表单数据
  account: '',
  password: '',
  repassword: '',
  identifyCode: ''
})

const rules = ref({
  account: [
    {
      required: true,
      message: '请输入账号',
      trigger: 'blur'
    },
    {
      min: 3,
      max: 10,
      message: '用户名长度在 3 到 10 个字符',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 16,
      message: '密码长度在 6 到 16 个字符',
      trigger: 'blur'
    },
    {
      pattern: /^\S{6,10}$/,
      message: '6-10位字符，且不能出现空格',
      trigger: 'blur'
    }
  ],
  repassword: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 16,
      message: '密码长度在 6 到 16 个字符',
      trigger: 'blur'
    },
    {
      pattern: /^\S{6,10}$/,
      message: '6-10位字符，且不能出现空格',
      trigger: 'blur'
    },
    {
      // 自定义验证器
      validator: (rule, value, callback) => {
        // 判断pssword 与 repassword 必须一致
        if (value !== formModel.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 获取表单对象
const form = ref()

// 注册
const register = async () => {
  // // 等待表单验证
  await form.value.validate()
  console.log(formModel.value)

  const registerFrom = ref({
    account: formModel.value.account,
    password: formModel.value.password
  })
  // 发送请求
  await doctorRegisterService(registerFrom.value)
  // 验证请求结果
  // 验证通过, 发送请求
  ElMessage.success('注册成功')
  // 切换到登录
  isRegister.value = false
}

// 登录
const login = async () => {
  // 验证验证码, 忽略大小写
  if (
    formModel.value.identifyCode.toUpperCase() !==
    identifyCode.value.toUpperCase()
  ) {
    ElMessage.error('验证码错误')
    return
  }
  // 等待表单验证
  // 校验方式: 调用 validate 方法
  await form.value.validate()
  // 验证通过, 发送请求
  const loginFrom = ref({
    account: formModel.value.account,
    password: formModel.value.password
  })
  const result = await doctorLoginService(loginFrom.value)
  doctorStore.setToken(result.data.data.token)

  // 成功提示
  ElMessage.success('登录成功')
  // 切换到首页
  router.push('/')
}

// 监听切换登录注册
watch(isRegister, () => {
  // 重置表单
  formModel.value = {
    account: '',
    password: '',
    repassword: ''
  }
})

// 图片验证码
let identifyCode = ref('')
const identifyCodes = '3456789ABCDEFGHGKMNPQRSTUVWXY'

// 切换验证码
const refreshCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes, 4)
}

// 生成验证码
const makeCode = (codes, length) => {
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(
      Math.random() * codes.length
    )
    identifyCode.value += codes[randomIndex]
  }
}

// 初始化生成验证码
refreshCode()
</script>

<template>
  <div class="container">
    <!-- 左侧轮播图 -->
    <div class="left-card">
      <el-carousel
        height="600px"
        direction="vertical"
        motion-blur
        :autoplay="true"
      >
        <el-carousel-item
          v-for="image in imageList"
          :key="image"
          class="carousel-item"
        >
          <img
            :src="image"
            class="rounded-image"
            fit="cover"
          />
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 登录注册切换 -->
    <div class="login-container">
      <!-- 注册表单 -->
      <el-card>
        <el-form
          class="form"
          :model="formModel"
          :rules="rules"
          ref="form"
          size="large"
          autocomplete="off"
          v-if="isRegister"
        >
          <el-form-item class="form-title">
            <h1>专家注册</h1>
          </el-form-item>
          <el-form-item prop="account">
            <el-input
              v-model="formModel.account"
              :prefix-icon="User"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="formModel.password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
              show-password="true"
            ></el-input>
          </el-form-item>
          <el-form-item prop="repassword">
            <el-input
              v-model="formModel.repassword"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入再次密码"
              show-password="true"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="register()"
              class="button"
              type="primary"
              auto-insert-space
            >
              注册
            </el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link
              type="info"
              :underline="false"
              @click="isRegister = false"
            >
              ← 返回
            </el-link>
          </el-form-item>
        </el-form>

        <!-- 登录表单 -->
        <el-form
          class="form"
          :model="formModel"
          :rules="rules"
          ref="form"
          size="large"
          autocomplete="off"
          v-else
        >
          <el-form-item class="form-title">
            <h1>专家登录</h1>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="formModel.account"
              :prefix-icon="User"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="formModel.password"
              name="password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
              show-password="true"
            ></el-input>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item>
            <el-input
              v-model="formModel.identifyCode"
              name="password"
              :prefix-icon="CircleCheck"
              type="text"
              placeholder="请输入验证码"
              :style="{ width: '60%' }"
            ></el-input>
            <span
              @click="refreshCode()"
              :style="{ cursor: pointer }"
            >
              <identify-picture
                :identifyCode="identifyCode"
              ></identify-picture>
            </span>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-form-item class="flex">
            <div class="flex">
              <el-checkbox>记住我</el-checkbox>
              <el-link
                class="forget-password"
                type="primary"
                :underline="false"
                >忘记密码？</el-link
              >
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="login"
              class="button"
              type="primary"
              auto-insert-space
              >登录</el-button
            >
          </el-form-item>
          <el-form-item class="flex">
            <el-link
              type="info"
              :underline="false"
              @click="isRegister = true"
            >
              注册 →
            </el-link>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  // 使用弹性布局
  display: flex;
  justify-content: center;
  align-items: center;

  // 设置渐变背景
  background: linear-gradient(
    to bottom right,
    #4a769c64,
    #e5e5e5
  );
  // 设置宽高
  width: 100%;
  height: 100vh;

  .left-card {
    width: 500px;
    height: 600px;
  }

  .login-container {
    // 设置居中
    .el-card {
      width: 500px;
      height: 600px;
      // 居中
      display: flex;
      justify-content: center;
      align-items: center;
      .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;
        width: 300px;
        height: 90%;

        .h1 {
          text-align: center;
        }
      }
    }
  }
}

.flex {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.el-card {
  // 取消阴影
  box-shadow: none;
  // 取消边框
  border: none;
  // 取消圆角
  border-radius: 0;
}

.button {
  width: 100%;
}
</style>
